using Microsoft.EntityFrameworkCore;
using RAG.Domain.Entities.App;
using RAG.Domain.Repositories;
using RAG.Infrastructure.Data;
using RAG.Application.Services.Interfaces;
using RAG.Application.Dtos.Permission;

namespace RAG.Application.Services.Implementations;

public class PermissionService : IPermissionService
{
    private readonly IRepository<Permissions> _permissionRepository;
    private readonly RagAIDbContext _context;

    public PermissionService(IRepository<Permissions> permissionRepository, RagAIDbContext context)
    {
        _permissionRepository = permissionRepository;
        _context = context;
    }

    public async Task<IEnumerable<PermissionDto>> GetAllPermissionsAsync()
    {
        var permissions = await _permissionRepository.GetAllAsync();
        return permissions.Select(p => new PermissionDto
        {
            Id = p.Id,
            PermissionName = p.PermissionName,
            CreatedAt = p.CreatedAt,
            UpdatedAt = p.UpdatedAt
        });
    }

    public async Task<PermissionDto?> GetPermissionByIdAsync(Guid id)
    {
        var permission = await _permissionRepository.GetByIdAsync(id);
        if (permission == null) return null;

        return new PermissionDto
        {
            Id = permission.Id,
            PermissionName = permission.PermissionName,
            CreatedAt = permission.CreatedAt,
            UpdatedAt = permission.UpdatedAt
        };
    }

    public async Task<PermissionDto> CreatePermissionAsync(PermissionDto permissionDto)
    {
        // 检查权限名称是否已存在
        var existingPermission = await _context.Permissions
            .FirstOrDefaultAsync(p => p.PermissionName == permissionDto.PermissionName);
        
        if (existingPermission != null)
        {
            throw new InvalidOperationException($"权限名称 '{permissionDto.PermissionName}' 已存在");
        }

        var permission = new Permissions
        {
            Id = Guid.NewGuid(),
            PermissionName = permissionDto.PermissionName,
            CreatedAt = DateTime.UtcNow,
            UpdatedAt = DateTime.UtcNow
        };

        var createdPermission = await _permissionRepository.CreatedAsync(permission);
        
        return new PermissionDto
        {
            Id = createdPermission.Id,
            PermissionName = createdPermission.PermissionName,
            CreatedAt = createdPermission.CreatedAt,
            UpdatedAt = createdPermission.UpdatedAt
        };
    }

    public async Task<PermissionDto> UpdatePermissionAsync(Guid id, PermissionDto permissionDto)
    {
        var existingPermission = await GetPermissionByIdAsync(id);
        if (existingPermission == null)
        {
            throw new InvalidOperationException($"权限ID '{id}' 不存在");
        }

        // 检查权限名称是否与其他权限冲突
        var duplicatePermission = await _context.Permissions
            .FirstOrDefaultAsync(p => p.PermissionName == permissionDto.PermissionName && p.Id != id);
        
        if (duplicatePermission != null)
        {
            throw new InvalidOperationException($"权限名称 '{permissionDto.PermissionName}' 已存在");
        }

        var permission = await _permissionRepository.GetByIdAsync(id);
        if (permission == null)
        {
            throw new InvalidOperationException($"权限ID '{id}' 不存在");
        }

        // 更新字段
        permission.PermissionName = permissionDto.PermissionName;
        permission.UpdatedAt = DateTime.UtcNow;

        var updatedPermission = await _permissionRepository.UpdateAsync(permission);
        
        return new PermissionDto
        {
            Id = updatedPermission.Id,
            PermissionName = updatedPermission.PermissionName,
            CreatedAt = updatedPermission.CreatedAt,
            UpdatedAt = updatedPermission.UpdatedAt
        };
    }

    public async Task<bool> DeletePermissionAsync(Guid id)
    {
        var permission = await GetPermissionByIdAsync(id);
        if (permission == null)
        {
            return false;
        }

        // 检查权限是否被角色使用
        var rolesUsingPermission = await _context.Roles
            .Where(r => r.PermissionList.Any(p => p.Id == id))
            .ToListAsync();

        if (rolesUsingPermission.Any())
        {
            var roleNames = string.Join(", ", rolesUsingPermission.Select(r => r.RoleName));
            throw new InvalidOperationException($"无法删除权限，该权限正在被以下角色使用: {roleNames}");
        }

        await _permissionRepository.DeleteAsync(id);
        return true;
    }
} 